// 待办工单 -》 通信光缆巡视 -》 光缆核查
<template>
  <view class="cable-inspect-main">
    <nav-bar class="header" back title="光缆巡视" @goBack="goBack"/>
    <view class="main-container">
      <!--光缆信息-->
      <plateTitle title="光缆信息" :isRequired="false" class="plate-title-1 cable-title"/>
      <view class="base-info-container">
        <van-cell-group>
          <van-cell v-for="(item,index) in taskDetail.baseInfoData" :key="index" :title="item.title" :value="item.value">
            <template #right-icon v-if="item.title === '实物ID'">
              <span class="operation"><img src="../../../../static/img/scan.png" alt=""></span>
            </template>
          </van-cell>
        </van-cell-group>
      </view>
      
      <!--巡视信息-->
      <plateTitle title="巡视信息" class="plate-title-2"/>
      <view class="patrol-info-container">
        <van-field
          readonly
          clickable
          input-align="right"
          right-icon="arrow"
          :value="isCoincide"
          label="台账信息与现场信息是否一致"
          placeholder="点击选择"
          @click="showPicker = true"
        />
        <van-radio-group v-show="isCoincide === '不一致'"
                         v-model="operation"
                         icon-size="15px"
                         checked-color="#417ADC">
          <van-radio name="noExist">现场无此设备，将标记此设备状态为“不存在”</van-radio>
          <van-divider dashed/>
          <van-radio name="modify">现场设备信息不一致，将标记此设备状态为“修改”</van-radio>
        </van-radio-group>
      </view>
      
      <!--按钮-->
      <van-button block @click="confirm">{{ buttonText() }}</van-button>
      
      <!--选择器-->
      <van-popup v-model="showPicker" position="bottom">
        <van-picker
          show-toolbar
          :columns="columns"
          @confirm="onConfirm"
          @cancel="showPicker = false"
        />
      </van-popup>
    
    </view>
  </view>
</template>

<script>
import navBar from "../../../../components/common/nav-bar";
import plateTitle from "../../../../components/business/plateTitle";
import { mapGetters } from "vuex";
import {Dialog, Toast} from "vant";

let map_obj = {
  "NAME": "光缆名称",           //	String	光缆名称
  "A_SITE_NAME": "起点名称",    //	String	起点名称
  "Z_SITE_NAME": "终点名称",    //	String	终点名称
  "VOLTAGE_CLASS": "电压等级",  //	String	电压等级
  "OPTICALORDER": "光缆顺序",   //	String	光缆顺序
  "FIBER_TYPE": "光缆种类",     //	String	光缆种类
  "POWER_LINE": "所属线路",     //	String	所属线路
  "LENGTH": "长度(Km)",         //	int	长度
  "LINE_NUMBER": "纤芯总数",   //	int	纤芯总数
  "RUN_STATE": "运行状态"     // String 运行状态
  // "TASK_ID": "",        //	String	主工单id
  // "OBJ_ID": "",         //	String	光缆巡视id
  // "IS_EXIST": "",       //	String	此光缆是否巡视过
  // "FRONT_FIBER_ID": "", //	String	对端光缆的巡视id
};
export default {
  components: {navBar, plateTitle},
  data() {
    return {
      fiberId: "", // 光缆id
      tourId: "", // 光缆巡视id
      taskId: "", // 工单id
      taskDetail: {
        originData: {},
        baseInfoData: {}
      },
      baseInfoData: [],
      buttonText: () => {
        if (this.isCoincide === "一致") return "保存";
        if (this.operation === "noExist") return "保存";
        if (this.operation === "modify") return "去完善台账信息";
      },
      isCoincide: "不一致",
      showPicker: false,
      columns: ["一致", "不一致"],
      operation: "modify", // 默认值
      isSynchronize: "0", // 是否同步（是；1；否：0）
      reTourCheck: '1', // 巡视-1 重新编辑-0
    };
  },
  computed: {
    ...mapGetters(['userData']),
  },
  onLoad(options) {
    this.fiberId = options.fiberId;
    this.tourId = options.tourId;
    let requestParams = {
      "batchId": this.userData.batchId, //	string	批次id
      "fiberId": options.fiberId, //	string	光缆id
      "fiber_exam_id": options.tourId, //	string	光缆巡视id
    };
    this.getBaseInfo(requestParams);
  },
  methods: {
    goBack() {
      uni.navigateTo({
        url: `/pages/workBench/todoTask/cableTour/cableTour?taskId=${this.taskId}`
      });
    },
    onConfirm(value) {
      this.isCoincide = value;
      this.showPicker = false;
    },
    // 获取光缆信息
    getBaseInfo(params) {
      this.$api.todoTaskApi.fiberExamineMsg(params).then(res => {
        this.taskId = res.data.TASK_ID;
        // todo: 同步对端判断，2023.3.18要求去掉，暂时注释
        // // 如果对端已巡视
        // if(res.data.IS_EXIST === 1) {
        //   Dialog.confirm({
        //     title: "对端光缆已巡视，是否同步？",
        //   }).then(() => { // 确认
        //     this.isSynchronize = "1";
        //     // 选择同步-》获取对端信息
        //     this.getFrontFiberMsg(params.fiberId, res.data);
        //   }).catch(() => { // 取消
        //     this.isSynchronize = "0";
        //     // 选择不同步-》显示当前光缆信息
        //     this.taskDetail = {
        //       originData: res.data,
        //       baseInfoData: Object.keys(map_obj).map(key => {
        //         return {
        //           title: map_obj[key],
        //           value: res.data[key]
        //         }
        //       })
        //     }
        //   });
        // }
        // // 如果对端未巡视，则显示当前光缆信息
        // else {
        //   this.taskDetail = {
        //     originData: res.data,
        //     baseInfoData: Object.keys(map_obj).map(key => {
        //       return {
        //         title: map_obj[key],
        //         value: res.data[key]
        //       }
        //     })
        //   }
        // }
        this.taskDetail = {
          originData: res.data,
          baseInfoData: Object.keys(map_obj).map(key => {
            return {
              title: map_obj[key],
              value: res.data[key]
            }
          })
        }
      });
    },
    
    // 获取对端光缆信息
    getFrontFiberMsg(fiberId, fiberData) {
      let params = {
        fiber_exam_id: this.tourId,
        front_fiber_id: fiberData.FRONT_FIBER_ID,
        front_service_state: fiberData.FRONT_SERVICE_STATE,
      }
      
      this.$api.todoTaskApi.frontFiberMsg(params).then(res => {
        this.taskDetail = {
          originData: res.data,
          baseInfoData: Object.keys(map_obj).map(key => {
            return {
              title: map_obj[key],
              value: res.data[key]
            }
          })
        }
        if (fiberData.FRONT_SERVICE_STATE === "1") {         // 一致
          this.isCoincide = "一致";

        } else if (fiberData.FRONT_SERVICE_STATE === "2") {  // 不存在
          this.isCoincide = "不一致";
          this.operation = "noExist";
        } else if (fiberData.FRONT_SERVICE_STATE === "4") {  // 更新
          this.isCoincide = "不一致";
          this.operation = "modify";
          uni.navigateTo({
            url: `/pages/workBench/todoTask/cableTour/completeCableInfo?taskId=${this.taskId}&tourId=${this.tourId}&fiberId=${this.fiberId}&frontFiberInfo=${JSON.stringify(res.data)}`
          });
        }
      });
    },
    confirm() {
      let params = {
        "reTourCheck": this.reTourCheck, // 巡视-1 重新编辑-0
        "batchId": this.userData.batchId, // 是 string 批次id
        "service_state": "",  //	是	string	设备状态（1：一致2：不存在 3：新增 4：更新）
        "userId": this.userData.userId,         //	是	string	用户id
        "fiber_exam_id": this.tourId,  //	是	string	光缆巡视id
        "userName": this.userData.userName,       //	是	string	用户名称
        "front_fiber_id": this.isSynchronize === "1" ? this.taskDetail.originData.OBJ_ID : "", //	否	string	对端光缆巡视id（若提示信息点击确认必传）
        "click_flag": this.isSynchronize,     //	否	string	提示信息标识（确认；1；取消：0）
        "task_id": this.taskId
      }
  
      if(this.isCoincide === "一致" || (this.isCoincide === "不一致" && this.operation === "noExist")) {
        Dialog.confirm({
          message: "所选巡视结果是否确认？确认后不可变更，如有问题请联系运维人员。",
        }).then(() => {
          if (this.isCoincide === "一致") {            // 一致
            params.service_state = "1";
            this.$api.todoTaskApi.fiberExamine(params).then(res => {
      
              if(res.code === 0) {
                // 如果当前为巡视，且返回data为0，表示重复巡视
                if(this.reTourCheck === '1' && res.data === 0) {
                  Dialog.confirm({
                    message: "该光缆已被巡视，请返回重试",
                  }).then(() => {
                    this.goBack();
                  });
                }
                else {
                  Dialog.confirm({
                    message: "保存成功，是否继续核查纤芯？",
                    confirmButtonText: "继续核查",
                    cancelButtonText: "返回列表"
                  })
                    .then(() => {
                      // on confirm
                      uni.navigateTo({
                        url: `/pages/workBench/todoTask/cableTour/cableDetail/cableDetail?tourId=${this.tourId}`
                      });
                    })
                    .catch(() => {
                      // on cancel
                      this.goBack();
                    });
                }
              }
      
              else {
                Toast.fail("操作失败");
              }
      
            })
          }
          if (this.isCoincide === "不一致" && this.operation === "noExist") {  // 不一致-》不存在
            params.service_state = "2";
            this.$api.todoTaskApi.fiberExamine(params).then(res => {
      
              if(res.code === 0) {
        
                // 如果当前为巡视，且返回data为0，表示重复巡视
                if(this.reTourCheck === '1' && res.data === 0) {
                  Dialog.confirm({
                    message: "该光缆已被巡视，请返回重试",
                  }).then(() => {
                    this.goBack();
                  });
                }
        
                else {
                  Toast.success({
                    message: '保存成功',
                    onOpened: () => {
                      this.goBack();
                    }
                  });
                }
        
              }
      
              else {
                Toast.fail("操作失败");
              }
      
            })
          }
        }).catch(() => {})
      }
    
      if (this.isCoincide === "不一致" && this.operation === "modify") {   // 不一致-》修改
        uni.navigateTo({
          url: `/pages/workBench/todoTask/cableTour/completeCableInfo?taskId=${this.taskId}&tourId=${this.tourId}&fiberId=${this.fiberId}`
        });
      }
    }
  },
};
</script>

<style scoped lang="scss">
.cable-inspect-main {
  .header {
    position: sticky;
    top: 0;
    z-index: 9;
  }
  
  .main-container {
    min-height: calc(100vh - #{px2vh(283)});
    padding: px2vh(30) px2vw(30) px2vh(90) px2vw(30);
    background-color: #F8F8F8;
    
    /deep/.van-field__label, 
    /deep/.van-field__control:read-only, 
    /deep/.van-field__body .van-field__control,
    /deep/.van-cell-group .van-cell
    {
      font-size: px2vw(42);
    }
    /deep/.van-field__label {
      width: auto;
    }
    
    .plate-title-1 {
      margin-top: px2vh(30);
      margin-bottom: px2vh(27);
    }
    
    .base-info-container {
      border-radius: $border-radius-base;
      overflow: hidden;
      background-color: #FFFFFF;
      
      .operation {
        margin-left: px2vw(30);
        
        img {
          width: px2vw(42);
          vertical-align: text-top;
        }
      }
    }
    
    .plate-title-2 {
      margin-top: px2vh(60);
      margin-bottom: px2vh(27);
    }
    
    .patrol-info-container {
      font-size: px2vw(42);
      color: #666666;
      border-radius: $border-radius-base;
      overflow: hidden;
      background-color: #FFFFFF;
      
      .van-radio-group {
        font-size: px2vw(42);

        padding: px2vh(60) px2vw(42);
      }
      
      /deep/ .van-field__label {
        font-size: px2vw(42);
        width: auto;
      }
    }
    
    /deep/ .van-button {
      margin-top: px2vh(100);
      height: px2vh(120);
      color: #fff;
      background-color: #417ADC;
      border: 1px solid #417ADC;
      border-radius: px2vh(60);
    }
  }
}
</style>